<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2025/6/12
 * Time: 16:49
 */

namespace app\service;


use app\model\Order;

class Kuaimai
{
    private $userId = 900025311;
    private $stockId = 2042;
    public function __construct(){
        $this->token();
    }

    public function token(){
        $token = cache('kuaimai_token');
        if (empty($token)) {
            $token = $this->getToken();
        }
        return $token;
    }

    public function stock(){
        $method = 'erp.warehouse.list.query';
        $res = $this->sendPostRequest($method,[]);
        return $res;
    }

    public function delivery($order){
        $method = 'erp.trade.consign';
        $res = $this->sendPostRequest($method,['sid' => $order]);
        return $res;
    }

    public function refund($reason){
        $method = 'erp.aftersale.workorder.create';
        $res = $this->sendPostRequest($method,[
            'refundWarehouseId' => $this->stockId,
            'reason' => $reason
        ]);
        return $res;
    }

    public function order(Order $find){
        $method = 'erp.trade.list.query';
        $this->token();
        $data = [
            'tid' => $find->order_no,
            'userId' => $this->userId,
            'status' => 'WAIT_BUYER_PAY',
            'receiverName' => $find->nickname,
            'receiverState' => $find->p,
            'receiverCity' => $find->c,
            'receiverDistrict' => $find->a,
            'receiverStreet' => '',
            'receiverAddress' => $find->address,
            'receiverMobile' => $find->mobiel,
            'orders' => [],
            'payment' => $find->amount,
        ];
        foreach ($find->record AS $key => $value) {
            $data['orders'][] = [
                'outerId' => '',
                'price' => $value->price,
                'num' => $value->number,
                'payment' => bcmul($value->price,$value->number,2)
            ];
        }
        $data['orders'] = json_encode($data['orders']);
        $res = $this->sendPostRequest($method,$data);
        return $res;
    }

    public function goods(){
        $method = 'item.list.query';
        $res = $this->sendPostRequest($method,[]);
        return $res;
    }

    public function label(){
        $method = 'erp.item.tag.list';
        $res = $this->sendPostRequest($method,[]);
        return $res;
    }

    public function classify(){
        $method = 'erp.item.seller.cat.list.get';
        $res = $this->sendPostRequest($method,[]);
        return $res;
    }

    public function close(array $order_no){
        $method = 'erp.trade.cancel';
        $res = $this->sendPostRequest($method,[
            'tids' => implode(',',$order_no),
        ]);
        return $res;
    }

    public function dianid(){
        $method = 'erp.shop.list.query';
        $res = $this->sendPostRequest($method,[]);
        return $res;
    }

    public function orderlist(){
        $method = 'erp.shop.list.query';
        $res = $this->sendPostRequest($method,[]);
        return $res;
    }

    public function getToken(){
        $method = 'open.token.refresh';
        $token = md5(uniqid());
        cache('kuaimai_token',$token,86400 * 2);
        $res = $this->sendPostRequest($method,[
            'refreshToken' => $token
        ]);
        return $res;
    }

    /**
     * 发送POST请求到指定URL
     *
     * @param string $url 请求的URL
     * @param string $appKey 分配给应用的AppKey
     * @param string $appSecret 应用的AppSecret，用于签名
     * @param string $accessToken 授权会话信息（access_token）
     * @param string $method API接口名称
     * @param string $version API协议版本
     * @param string $signMethod 签名的摘要算法，默认为hmac
     * @param string $format 响应格式，默认为json
     * @return array 返回API的响应结果
     */
    protected  function sendPostRequest($method,$data) {
        $url = 'https://gw.superboss.cc/router';
        $appKey = '1531704296';
        $appSecret = '23a844ae6ac647b79c4cfd86323158f4';
        $accessToken = '75bebd67fe634ee0950c939f525d7424';
        // 准备请求参数
        $params['method'] = $method;
        $params['appKey'] = $appKey;
        $params['timestamp'] = date('Y-m-d H:i:s');
        $params['format'] = 'json';
        $params['session'] = $accessToken;
        $params['version'] = '1.0';
        $params['sign_method'] = 'md5';
        $params = array_merge($params,$data);
        $paramsStr = '';
        ksort($params);
        // 生成待签名的字符串
        foreach ($params as $key => $value) {
            if ($key && strlen($value) > 0)
                $paramsStr = $paramsStr . $key . $value;
        }
        $paramsStr = $appSecret . $paramsStr . $appSecret;
        $params['sign'] = strtoupper(md5($paramsStr));
        // 根据sign_method生成签名
//        dd($params);
        $data = http_build_query($params);
        $opts = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type: application/x-www-form-urlencoded',
                'content' => $data
            )
        );
        $context = stream_context_create($opts);
        $html = file_get_contents($url, false, $context);
        $result = json_decode($html, true);dd($result);
        return $result;
    }
}